package com.codeplex.jtfscli.commands;

import java.util.List;
import java.util.Map;

import com.codeplex.jtfscli.util.TFSConnectionFactory;
import com.codeplex.jtfscli.util.TextTable;
import com.microsoft.tfs.core.clients.versioncontrol.VersionControlConstants;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;

public class WorkspacesCommand extends Command {
	public WorkspacesCommand(TFSConnectionFactory connectionFactory) {
		super(connectionFactory);
	}

	public WorkspacesCommand() {
		super();
	}

	@Override
	public void run(final Map<String, String> parsedArgs,
			final List<String> regularArgs, final String username,
			final String password) throws Exception {
		final String owner, computer;
		if (parsedArgs.containsKey("-owner"))
			owner = parsedArgs.get("-owner");
		else
			owner = VersionControlConstants.AUTHENTICATED_USER;
		if (parsedArgs.containsKey("-computer"))
			computer = parsedArgs.get("-computer");
		else
			computer = java.net.InetAddress.getLocalHost().getHostName();
		run(parsedArgs.get("-server"), owner, computer, username, password);
	}

	public void run(final String server, final String owner,
			final String computer, final String usernameAndDomain,
			final String password) {
		final TextTable table = new TextTable("Workspace", "Owner", "Computer",
				"Comment");
		for (final Workspace w : connectionFactory
				.createConnection(server, usernameAndDomain, password)
				.getVersionControlClient()
				.queryWorkspaces(null, owner, computer))
			table.add(w.getName(), w.getOwnerName(), w.getComputer(),
					w.getComment());
		System.out.println(table);
	}
}
